<template>
	<div
		:class="[
			'app-editor-container',
			'app-checkbox-list',
			`app-checkbox-list-${name}`,
			`app-checkbox-list-${size}`,
			`app-checkbox-list-${button ? 'button' : border ? 'border' : 'default'}`,
		]"
	>
		<a-checkbox-group
			@change="onChange"
			:value="selectArray"
			:options="items"
			:disabled="disabled || readOnly"
		>
		</a-checkbox-group>
	</div>
</template>
<script setup lang="ts">
import { ICodeListItem, IEvent, typeOf } from '@/core';
import { computed, onBeforeMount, ref, Ref } from 'vue';
import { checkboxListProps } from './checkbox-list';
import { handleEditorNavParams, useEditorTypeParams } from '@/hooks/use-editor';

interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(checkboxListProps);
const emit = defineEmits<EditorEmit>();
// 类型校验
const { validateConfig, valueType, valueSeparator } = useEditorTypeParams();
validateConfig();
const { navContext, navViewParam } = handleEditorNavParams(props);
let items: Ref<any[]> = ref([]);
const selectArray: Ref<any[]> = computed(() => {
	if (props.value) {
		let selects: any[] = [];
		if (Array.isArray(props.value)) {
			selects = props.value;
		} else {
			selects = props.value.split(valueSeparator || props.valueSeparator);
		}
		if (props.codeItemValueNumber || props.mode == 'number') {
			for (let i = 0; i < selects.length; i++) {
				selects[i] = parseInt(selects[i]);
			}
		}
		return selects;
	} else {
		return [];
	}
});

const onChange = ($event: any[]) => {
	let value: null | string | string[] = null;
	let _datas: string[] = [];
	items.value.forEach((item: any) => {
		const index = $event.findIndex((_key: any) => Object.is(item.value, _key));
		if (index === -1) {
			return;
		}
		_datas.push(item.value);
	});
	value = _datas.join(valueSeparator || props.valueSeparator);
	if (valueType === 'SIMPLES') {
		value = _datas;
	}
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: value,
	});
};

const formatCodeList = (items: Array<any>) => {
	let matching = false;
	let result: Array<any> = [];
	try {
		items.forEach((item: any) => {
			const type = typeOf(item.value);
			if (type != props.valueType) {
				matching = true;
				if (type === 'number') {
					item.value = item.value.toString();
				} else {
					if (type == 'null') {
						props.valueType == 'number' ? (item.value = 0) : (item.value = '');
					} else if (item.value.indexOf('.') == -1) {
						item.value = parseInt(item.value);
					} else {
						item.value = parseFloat(item.value);
					}
				}
			}
			result.push(item);
		});
		if (matching) {
			console.warn(
				App.ts(
					'common.generic.codelistcast',
					'代码表值类型和属性类型不匹配，自动强制转换'
				)
			);
		}
		return result;
	} catch (error) {
		console.warn(
			App.ts(
				'common.generic.codelistwarn',
				'代码表值类型和属性类型不匹配，自动强制转换异常，请修正代码表值类型和属性类型匹配'
			)
		);
		return [];
	}
};

onBeforeMount(() => {
	loadData();
});

const loadData = async () => {
	if (props.codeListTag && props.codeListType) {
		const codeListResult = await App.getAppCodeListHelper().getCodeListItems(
			props.codeListTag,
			navContext,
			navViewParam
		);
		if (codeListResult.ok) {
			const result = formatCodeList(codeListResult.data);
			result.forEach((item: ICodeListItem) => {
				items.value.push({ ...item, label: item.text });
			});
		}
	}
};
</script>
